#!/usr/bin/python3
#-*- coding:UTF-8 -*-
"""
@file
@author          mening
@date            2024-03-01 10:13:01
@copyright       Copyright (c) 2024 by 北京长扬科技有限公司, ALL Rights Reserved.
@details         获取指定目录的所有rpm包，解压到指定目录
"""

import os
import re
import glob
import subprocess


work_path = '/opt/rpm-file/work-root/'
"""获取当前目录,并拼接rpm包所在目录,注意得写绝对路径"""
rpm_debuginfo_directory = '/opt/rpm-file/debuginfo-dir/'
print(('[debug1]:存放debuginfo包目录为: ' + rpm_debuginfo_directory))

rpm_directory = '/opt/rpm-file/RPMS/'

if not os.path.exists(work_path):
    print('[debug]:没有检测到工作目录 ' + work_path + ' 正在创建...')
    os.system('mkdir -p ' + work_path)

os.chdir(work_path)
print('[debug]:当前目录脚本所在目录为: ' + os.getcwd() )

"""读取目录中所有rpm包文件名到数组中"""
rpm_files = glob.glob(os.path.join(rpm_directory,'*.rpm'))
"""print('[debug2]:',rpm_files)"""
"""
带管道的shell命令
command = "ls ../RPMS/ | wc -l "
process = subprocess.Popen(command,\
                            shell = True,\
                            stdout = subprocess.PIPE,\
                            stderr = subprocess.PIPE)
stdout,stderr = process.communicate()
print(stdout.decode('utf-8'))
"""
"""从数组中获取rpm包,执行rpm2cpio解压到当前目录"""
new_filed = '-debuginfo'

for rpm_file in rpm_files:
    command = "rpm2cpio " + rpm_file + " | cpio -div"
    print('[debug]:command is: ',command)
    process = subprocess.Popen(command,\
                               shell=True,\
                               stdout=subprocess.PIPE,\
                               stderr=subprocess.PIPE)
    stdout,stderr = process.communicate()
    print('[debug]:returncode is: ',process.returncode)
    (rpm_dir, rpm_name) = os.path.split(rpm_file)
    pattern = r'-([0-9].*).rpm'
    new_content = re.sub(pattern, new_filed + r"-\1", rpm_name, count=1, flags=re.MULTILINE)
    print('[debug1]:debuginfo pkg name is: ' + new_content)
    os.system('yum install -y --downloadonly --downloaddir=/opt/rpm-file/debuginfo-dir/ --disablerepo=* --enablerepo=debuginfo ' + new_content)
    print('[debug2]Check debuginfo rpm name is : '+ rpm_debuginfo_directory + new_content + '.rpm')
    if os.path.exists(rpm_debuginfo_directory + new_content +'.rpm'):
        command = "rpm2cpio " + rpm_debuginfo_directory + new_content + ".rpm | cpio -div"
        print('[debug2]:command is: ',command)
        process = subprocess.Popen(command,\
                                   shell=True,\
                                   stdout=subprocess.PIPE,\
                                   stderr=subprocess.PIPE)
        stdout,stderr = process.communicate()
        print('[debug3]:returncode is: ',process.returncode)

"""
以当前目录为根目录,全局将所有可以生成dump的库文件生成dump文件到指定目录
这一步不在这里写，复用dump-maker.py文件即可。
"""
